package com.das.mechanic_base.widget

import android.content.res.Resources
import android.graphics.*
import android.util.TypedValue
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.das.mechanic_base.R
import com.das.mechanic_base.adapter.common.X3HomeTaskAdapter
import com.das.mechanic_base.app.X3MyApp

class X3TaskItemDecoration() : RecyclerView.ItemDecoration(), RecyclerView.OnItemTouchListener {


    /**
     * 顶部的大小
     */
    private var topHeight = dp2px(34)

    /**
     * 顶部背景画笔
     */
    private var topPaint: Paint = Paint()

    /**
     *顶部文字画笔
     */
    private var topTextPaint = Paint()

    /**
     * 顶部文字大小
     */
    private var topTextSize = dp2px(14)

    /**
     * 顶部文字边距
     */
    private var topTextPadding = dp2px(20)
    private var topTextRect: Rect = Rect()


    /**
     * 分组头部的大小
     */
    private var headHeight = dp2px(34)

    /**
     * 分组头部背景画笔
     */
    private var headPaint: Paint = Paint()

    /**
     *分组头部文字画笔
     */
    private var headTextPaint = Paint()

    /**
     * 分组头部文字大小
     */
    private var headTextSize = dp2px(14)

    /**
     * 分组头部文字边距
     */
    public var headTextPadding = dp2px(20)

    private var headTextRect: Rect = Rect()

    private var expandBitmap: Bitmap? = null

    private var collaseBitmap: Bitmap? = null

    private var rlv_parent: RecyclerView? = null

    /**
     * 初始化画笔
     */
    init {
        topPaint.isAntiAlias = true
        topPaint.strokeWidth = 5f
        topPaint.style = Paint.Style.FILL
        //topPaint.color = Color.parseColor("#f5f5f5")

        topTextPaint.color = Color.parseColor("#707380")
        topTextPaint.style = Paint.Style.FILL
        topTextPaint.isAntiAlias = true
        topTextPaint.textSize = topTextSize.toFloat()

        headPaint.isAntiAlias = true
        headPaint.strokeWidth = 5f
        headPaint.style = Paint.Style.FILL
        //headPaint.color = Color.parseColor("#fff000")

        headTextPaint.color = Color.parseColor("#707380")
        headTextPaint.style = Paint.Style.FILL
        headTextPaint.isAntiAlias = true
        headTextPaint.textSize = headTextSize.toFloat()

        expandBitmap = BitmapFactory.decodeResource(X3MyApp.getInstance().getApp().getResources(), R.mipmap.x3_task_show)
        //line.setColor(Color.parseColor("#86FFE1"));
        collaseBitmap = BitmapFactory.decodeResource(X3MyApp.getInstance().getApp().getResources(), R.mipmap.x3_task_gone)

    }

    /**
     * onDraw先绘制，然后在轮到item,最后是onDrawOver
     * 绘制分组的头部
     */
    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        rlv_parent = parent
        parent.addOnItemTouchListener(this)
        if (parent.adapter is X3HomeTaskAdapter) {
            val adapter = parent.adapter as X3HomeTaskAdapter
            val count = parent.childCount
            val left = parent.paddingLeft
            val right = parent.width - parent.paddingRight

            //遍历所有子view
            for (i in 0 until count) {
                val view = parent.getChildAt(i)
                val childPosition = parent.getChildAdapterPosition(view)

                //在paddingTop范围内绘制
                if (view.top - headHeight >= parent.paddingTop) {
                    //如果是分组的头部
                    if (adapter.isGroupHead(childPosition)) {
                        val groupName = adapter.getGroupName(childPosition)

                        headPaint.color = Color.parseColor("#F5F5F7")
                        //绘制头部的背景
                        val rect = Rect(left, view.top - headHeight, right, view.top)
                        c.drawRect(rect, headPaint)

                        headTextPaint.color = Color.parseColor("#707380")
                        //绘制头部文字
                        headTextPaint.getTextBounds(groupName, 0, groupName.length, headTextRect)

                        c.drawText(
                                groupName,
                                (left + headTextPadding).toFloat(),
                                (view.top - (headHeight - headTextRect.height()) / 2 - dp2px(2)).toFloat(),
                                headTextPaint
                        )

                        if (adapter.isComplete(childPosition)) {
                            // 如果是已经完成的 需要绘制收起
                            val noticeName = adapter.getCompleteName()

                            headPaint.color = Color.parseColor("#F5F5F7")

                            headTextPaint.color = Color.parseColor("#0077ff")
                            //绘制头部文字
                            headTextPaint.getTextBounds(noticeName, 0, noticeName.length, headTextRect)

                            c.drawText(
                                    noticeName,
                                    (right - headTextPadding - headTextRect.width() - dp2px(13)).toFloat(),
                                    (view.top - (headHeight - headTextRect.height()) / 2 - dp2px(1)).toFloat(),
                                    headTextPaint
                            )

                            if (adapter.isExpand()) {
                                collaseBitmap?.let { it1 -> c.drawBitmap(it1, (right - headTextPadding - it1.width).toFloat(), (view.top  - (headHeight - it1.height) / 2 - dp2px(5)).toFloat(), headPaint) }

                            }else {
                                expandBitmap?.let { it1 -> c.drawBitmap(it1, (right - headTextPadding - it1.width).toFloat(), (view.top  - (headHeight - it1.height) / 2 - dp2px(5)).toFloat(), headPaint) }

                            }

                        }
                    }

                }
            }
        }
    }

    /**
     * 绘制吸顶效果
     */
    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        rlv_parent = parent
        parent.addOnItemTouchListener(this)
        if (parent.adapter is X3HomeTaskAdapter) {
            val adapter = parent.adapter as X3HomeTaskAdapter
            val layoutManager = parent.layoutManager
            //只考虑LinearLayoutManager
            if (layoutManager is LinearLayoutManager) {
                //找到RecyclerView第一个显示的view的position
                val position = layoutManager.findFirstVisibleItemPosition()
                //通过viewHolder获取itemView
                val childView = parent.findViewHolderForAdapterPosition(position)?.itemView

                val left = parent.paddingLeft
                val right = parent.width - parent.paddingRight
                val top = parent.paddingTop

                childView?.let {
                    //如果第一个可见itemView的下一个是组的头部，就把吸顶的顶上去
                    if (adapter.isGroupHead(position + 1)) {
                        //绘制吸顶头部的背景,bottom会随着上滑越来越小
                        val bottom = Math.min(topHeight, childView.bottom - top)
                        val rect = Rect(left, top, right, top + bottom)

                        topPaint.color = Color.parseColor("#F5F5F7")
                        c.drawRect(rect, topPaint)

                        //绘制吸顶的头部文字
                        val groupName = adapter.getGroupName(position)
                        topTextPaint.getTextBounds(groupName, 0, groupName.length, topTextRect)

                        //将超出的挡住裁掉
                        val clipRect = Rect(left, top + bottom, right, top)
                        c.clipRect(clipRect)

                        c.drawText(
                                groupName,
                                (left + topTextPadding).toFloat(),
                                (top + bottom - (topHeight - topTextRect.height()) / 2  - dp2px(2)).toFloat(),
                                topTextPaint
                        )
                    }
                    //如果第一个可见itemView的下一个不是组的头部，就直接绘制吸顶头部
                    else {
                        //绘制吸顶头部的背景
                        val rect = Rect(left, top, right, top + topHeight)

                        topPaint.color = Color.parseColor("#F5F5F7")

                        c.drawRect(rect, topPaint)

                        //绘制吸顶的头部文字
                        val groupName = adapter.getGroupName(position)

                        topTextPaint.getTextBounds(groupName, 0, groupName.length, topTextRect)

                        c.drawText(
                                groupName,
                                (left + topTextPadding).toFloat(),
                                (top + topHeight - (topHeight - topTextRect.height()) / 2 - dp2px(2)).toFloat(),
                                topTextPaint
                        )

                        if (adapter.isComplete(position)) {
                            // 如果是已经完成的 需要绘制收起
                            val noticeName = adapter.getCompleteName()

                            headPaint.color = Color.parseColor("#F5F5F7")

                            headTextPaint.color = Color.parseColor("#0077ff")
                            //绘制头部文字
                            headTextPaint.getTextBounds(noticeName, 0, noticeName.length, headTextRect)

                            c.drawText(
                                    noticeName,
                                    (right - headTextPadding - headTextRect.width() - dp2px(13)).toFloat(),
                                    (top + topHeight - (topHeight - headTextRect.height()) / 2 - dp2px(1)).toFloat(),
                                    headTextPaint
                            )

                            if (adapter.isExpand()) {
                                collaseBitmap?.let { it1 -> c.drawBitmap(it1, (right - headTextPadding - it1.width).toFloat(), (top + topHeight - (topHeight - it1.height) / 2 - dp2px(5)).toFloat(), headPaint) }

                            }else {
                                expandBitmap?.let { it1 -> c.drawBitmap(it1, (right - headTextPadding - it1.width).toFloat(), (top + topHeight - (topHeight - it1.height) / 2 - dp2px(5)).toFloat(), headPaint) }

                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * 设置itemView偏移大小
     */
    override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        if (parent.adapter is X3HomeTaskAdapter) {
            val adapter = parent.adapter as X3HomeTaskAdapter
            //RecyclerView的LayoutParams，是有viewHolder的，所以可以通过View 获取LayoutParams,再拿到ViewHolder
            //获取当前view对应的position
            val position = parent.getChildAdapterPosition(view)

            //判断分组头
            if (adapter.isGroupHead(position)) {
                outRect.set(0, headHeight, 0, 0)
            }
        }
    }

    fun dp2px(dp: Int): Int {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dp.toFloat(),
                Resources.getSystem().displayMetrics
        ).toInt()
    }

    override fun onTouchEvent(rv: RecyclerView, event: MotionEvent) {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                val x = event.x
                val adapter = rlv_parent?.adapter as X3HomeTaskAdapter

                if ((x >= (adapter.getWidth() - headTextPadding - headTextRect.width() - dp2px(13)).toFloat() && x <= adapter.getWidth())) {
                    adapter.changeExpand(!adapter.isExpand())
                }
            }
        }
    }

    override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
        val adapter = rv.adapter as X3HomeTaskAdapter

        val linearLayoutManager = rv.layoutManager as LinearLayoutManager

        val findFirstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition()

        val complete = adapter.isComplete(findFirstVisibleItemPosition)

        if (!complete && (e.y >= 0 && e.y <= topHeight)) {
            return !(!complete && (e.y >= 0 && e.y <= topHeight))
        }

        var top = linearLayoutManager.findViewByPosition(adapter.getAddIndex())?.bottom

        var bottom = linearLayoutManager.findViewByPosition(adapter.getAddIndex() + 1)?.top

        if (top == null) {
            return (e.x >= (adapter.getWidth() - headTextPadding - headTextRect.width() - dp2px(13)).toFloat() && e.x <= adapter.getWidth()) &&
                    (e.y >= 0 && e.y <= topHeight)
        }

        if (bottom == null) {
            bottom = 0
        }

        return (e.x >= (adapter.getWidth() - headTextPadding - headTextRect.width() - dp2px(13)).toFloat() && e.x <= adapter.getWidth()) &&
                (e.y >= top && e.y <= bottom)
    }

    override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {

    }
}